﻿using System.Xml.Linq;
using IcicleFramework;
using IcicleFramework.Components.Behaviors;
using IcicleFramework.Components.Metadata;
using IcicleFramework.Components.Physics;
using IcicleFramework.Inputs;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace ExampleGame.Components.Behaviors
{
    public class PlayerPaddleBehavior : BaseBehavior
    {
        protected Player Player { get; set; }

        protected Vector2 MaxVelocity { get; set; }

        public override IBehavior DeepClone()
        {
            return new PlayerPaddleBehavior();
        }

        public override void PostInitialize()
        {
            //Try to find the Metadata component and pull player information from it.
            IMetadataComponent metadataComponent = Parent.Parent.GetComponent<IMetadataComponent>();

            if (metadataComponent != null)
            {
                Player player = metadataComponent.GetMetadata("player") as Player;

                if (player != null)
                    this.Player = player;
            }

            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            Vector2 impulse = Vector2.Zero;
            Vector2 actualSpeed = MaxVelocity * (float) gameTime.ElapsedGameTime.TotalSeconds;

            if (Player != null)
            {
                if (Player.InputHandler.IsDown(Buttons.DPadLeft, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Left))
                {
                    impulse.X = -actualSpeed.X;
                }
                if (Player.InputHandler.IsDown(Buttons.DPadRight, Player.Controller) ||
                    Player.InputHandler.IsDown(Keys.Right))
                {
                    impulse.X = actualSpeed.X;
                }
            }

            if (impulse.X > 0f || impulse.X < 0f)
            {
                actionData.ClearData();
                actionData.AddData("impulse", impulse.X);

                Parent.FireSingleAction(Parent.Parent, ActionName, actionData);
            }

            base.Update(gameTime);
        }

        public override void Deserialize(XElement element)
        {
            MaxVelocity = new Vector2(float.MaxValue);
            XElement maxVelElement = element.Element("maxVelocity");
            if (maxVelElement != null)
            {
                MaxVelocity = MaxVelocity.DeserializeOffset(maxVelElement);
            }

            base.Deserialize(element);
        }
    }
}
